package com.gxg.dockerapi;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class DockerImageAPI
{
  static OkHttpClient client = new OkHttpClient();
  
  public static String queryAllImageInfo(String dockerServerIP)
    throws IOException
  {
    Request request = new Request.Builder().get().url(dockerServerIP + "/images/json").build();
    Response response = null;
    try
    {
      response = client.newCall(request).execute();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    return response.body().string();
  }
  
  public static int deleteImages(String dockerServerIP, String imageID)
  {
    Request request = new Request.Builder().delete().url(dockerServerIP + "/images/" + imageID + "?force=true").build();
    Response response = null;
    try
    {
      response = client.newCall(request).execute();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    return response.code();
  }
  
  public static int buileByDockerfile(String dockerServerIP, String dockerfilePath, String name, String tag)
  {
    Response response = null;
    RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), new File(dockerfilePath));
    
    Request request = new Request.Builder().post(requestBody).url(dockerServerIP + "/build?t=" + name + ":" + tag).build();
    try
    {
      response = client.newCall(request).execute();
      System.out.println("BuileByDockerfile" + request.toString());
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    return response.code();
  }
}
